<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-lx-cascades"></i> 接口管理
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container v2-group">
            <div class="handle-box">
                <el-input v-model="query.kw" placeholder="关键词" class="handle-input mr10" clearable></el-input>
                <el-button type="primary" icon="el-icon-search" @click="handleSearch">查询</el-button>
                <el-button
                    type="success"
                    icon="el-icon-plus"
                    class="handle-del mr10"
                    @click="handleAdd"
                >新增接口</el-button>
            </div>
            <el-table
                :data="tableData"
                border
                class="table"
                ref="multipleTable"
                header-cell-class-name="table-header"
                @selection-change="handleSelectionChange"
                stripe
            >
                <!-- <el-table-column type="selection" width="55" align="center"></el-table-column> -->
                <el-table-column prop="name" width="180" label="名称" show-overflow-tooltip></el-table-column>
                <el-table-column prop="use_case" label="用途" show-overflow-tooltip></el-table-column>
                <el-table-column prop="url" label="Url" show-overflow-tooltip></el-table-column>
                <el-table-column prop="update_time" label="更新时间" width="180"></el-table-column>
                <el-table-column label="操作" width="180">
                    <template slot-scope="scope">
                        <el-button
                            type="text"
                            icon="el-icon-edit"
                            @click="handleEdit(scope.$index, scope.row)"
                        >编辑</el-button>
                        <el-button
                            type="text"
                            icon="el-icon-delete"
                            class="red"
                            @click="handleDelete(scope.$index, scope.row)"
                        >删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination
                    background
                    layout="total, sizes, prev, pager, next, jumper"
                    :current-page="query.page"
                    :page-size="query.size"
                    :total="pageTotal"
                    @current-change="handlePageChange"
                    :page-sizes="[10, 20, 30, 40, 50, 100]"
                    @size-change="handleSizeChange"
                ></el-pagination>
            </div>
        </div>

        <!-- 编辑弹出框 -->
        <el-dialog title="编辑" :visible.sync="editVisible" width="530px">
            <el-form ref="entityEdit" :model="form" label-width="70px">
                <el-form-item label="名称" prop="name">
                    <el-input v-model="form.name"></el-input>
                </el-form-item>
                <el-form-item label="用途" prop="use_case">
                    <el-input v-model="form.use_case"></el-input>
                </el-form-item>
                <el-form-item label="Url" prop="Url">
                    <el-input v-model="form.url"></el-input>
                </el-form-item>
                <el-form-item label="参数列表" prop="params" class="dynamic-form">
                    <div class="algorithm-params" v-for="(item, index) in algorithmParams" :key="index">
                        <el-input v-model="item.name" placeholder="参数名称"></el-input>
                        <el-select v-model="item.data_type" placeholder="- 请选择数据类型 -" width="100%">
                            <el-option key="1" label="int" value="int"></el-option>
                            <el-option key="2" label="string" value="string"></el-option>
                            <el-option key="3" label="float" value="float"></el-option>
                        </el-select>
                        <el-button @click="deleteParam(index)">删除参数</el-button>
                    </div>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="addParam">添加参数</el-button>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveEdit">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 新增弹出框 -->
        <el-dialog title="新增" :visible.sync="addVisible" width="530px">
            <el-form ref="entityAdd" :model="form" :rules="rulesEntityAdd" label-width="120px">
                <el-form-item label="名称" prop="name">
                    <el-input v-model="form.name"></el-input>
                </el-form-item>
                <el-form-item label="用途" prop="use_case">
                    <el-input v-model="form.use_case"></el-input>
                </el-form-item>
                <el-form-item label="Url" prop="Url">
                    <el-input v-model="form.url"></el-input>
                </el-form-item>
                <el-form-item label="参数列表" prop="params" class="dynamic-form">
                    <div class="algorithm-params" v-for="(item, index) in algorithmParams" :key="index">
                        <el-input v-model="item.name" placeholder="参数名称"></el-input>
                        <el-select v-model="item.data_type" placeholder="- 请选择数据类型 -" width="100%">
                            <el-option key="1" label="int" value="int"></el-option>
                            <el-option key="2" label="string" value="string"></el-option>
                            <el-option key="3" label="float" value="float"></el-option>
                        </el-select>
                        <el-button @click="deleteParam(index)">删除参数</el-button>
                    </div>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="addParam">添加参数</el-button>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveAdd">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import api from '../../../api/index';
import sysdict from '../../../api/sysdict';

export default {
    name: 'basetable',
    data() {
        return {
            query: {
                address: '',
                name: '',
                kw: '',
                page: 1,
                size: 10
            },
            tableData: [
                {
                    name: 'user01',
                    surname: '张三',
                    size: '11KB',
                    update_time: '2024-11-01 00:00:00'
                }
            ],
            multipleSelection: [],
            delList: [],
            editVisible: false,
            pageTotal: 0,
            form: {},
            idx: -1,
            id: -1,
            addVisible: false,
            rulesEntityAdd: {
                file: [{ required: false, message: '请上传文件', trigger: 'blur' }],
                task_name: [{ required: true, message: '请输入任务名称', trigger: 'blur' }]
            },
            sysdict,
            algorithmParams: [],
            loading: false,
        };
    },
    created() {
        this.getData();
    },
    methods: {
        addParam() {
            var param = {name: '', data_type: '', editing: true};
            this.algorithmParams.splice(0, 0, param);
        },
        editParam(index) {
            this.algorithmParams[index].editing = true;
        },
        saveParam(index) {
            this.algorithmParams[index].editing = false;
            this.loading = true;
            if (this.algorithmParams[index].id === undefined) {
                api.addSourceGoal(Object.assign({}, this.algorithmParams[index], {source_id: this.form.source_id})).then(res => {
                    this.getGoals();
                    this.form.crawling_num += 1;
                }).catch(err => {
                    this.$message.error(err);
                    this.loading = false;
                });
            }
            else {
                api.updateSourceGoal(Object.assign({}, this.algorithmParams[index])).then(res => {
                    this.loading = false;
                }).catch(err => {
                    this.$message.error(err);
                    this.loading = false;
                });
            }
        },
        deleteParam(index) {
            console.log(index);
            this.algorithmParams.splice(index, 1);
        },
        // 获取 easy-mock 的模拟数据
        getData() {
            api.getEntryList(this.query).then(res => {
                this.tableData = res.items.map(element => {
                    var data = {};
                    Object.assign(data, element);
                    api.downloadBackup(element).then(resUrl => {
                        data.link = resUrl.url;
                    });
                    return data;
                });
                this.pageTotal = res.total;
            }).catch(err => {
                this.$message.error(err);
            });
        },
        // 触发搜索按钮
        handleSearch() {
            this.$set(this.query, 'page', 1);
            this.getData();
        },
        // 删除操作
        handleDelete(index, row) {
            // 二次确认删除
            this.$confirm('确定要删除吗？', '提示', {
                type: 'warning'
            })
            .then(() => {
                api.deleteEntry({pk: row.id}).then(res => {
                    this.$message.success('删除成功');
                    this.tableData.splice(index, 1);
                }).catch(err => {
                    this.$message.error(err);
                });
            })
            .catch(() => {});
        },
        // 多选操作
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        delAllSelection() {
            const length = this.multipleSelection.length;
            let str = '';
            this.delList = this.delList.concat(this.multipleSelection);
            for (let i = 0; i < length; i++) {
                str += this.multipleSelection[i].name + ' ';
            }
            this.$message.error(`删除了${str}`);
            this.multipleSelection = [];
        },
        // 编辑操作
        handleEdit(index, row) {
            this.idx = index;
            this.form = row;
            api.getEntryDetail({pk: row.id}).then(res => {
                this.algorithmParams = res.item.args;
                this.editVisible = true;
            }).catch(err => {
                this.$message.error(err);
            });
        },
        // 保存编辑
        saveEdit() {
            this.$refs.entityEdit.validate(valid => {
                if (valid) {
                    api.editEntry(Object.assign({}, this.form, {pk: this.form.id, args: JSON.stringify(this.algorithmParams)})).then(res => {
                        this.$message.success(`修改第 ${this.idx + 1} 行成功`);
                        this.editVisible = false;
                        this.getData();
                    }).catch(err => {
                        this.$message.error(err);
                    });
                } else {
                    return false;
                }
            });
        },
        //新增操作
        handleAdd() {
            this.form = {};
            this.addVisible = true;
            this.addParam();
        },
        saveAdd() {
            this.$refs.entityAdd.validate(valid => {
                if (valid) {
                    api.addEntry(Object.assign({}, this.form, {args: JSON.stringify(this.algorithmParams)})).then(res => {
                        this.$message.success(`新增成功`);
                        this.addVisible = false;
                        this.getData();
                    }).catch(err => {
                        this.$message.error(err);
                    });
                } else {
                    return false;
                }
            });
        },
        // 分页导航
        handlePageChange(val) {
            this.$set(this.query, 'page', val);
            this.getData();
        },
        handleSizeChange(val) {
            this.$set(this.query, 'size', val);
            this.getData();
        }
    }
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
.algorithm-params {
    border: 1px dashed #ddd;
    padding: 5px;
    text-align: right;
}
.algorithm-params .el-select {
    display: block;
}
:deep(.el-dialog) .dynamic-form {
    height: calc(70vh - 470px);
    overflow-y: scroll;
    padding-bottom: 5px;
}
</style>
